var Token = function (cookie) {

    this.cookie = cookie;
};

Token.prototype = {


    get: function (req) {

        var token = this.cookie.signed ? req.signedCookies[this.cookie.name] : req.cookies[this.cookie.name];
        if (token && !req.query.user) {
            try {
                token = JSON.parse(token);
                if (token) {

                    if (token.client === req.query.client || !req.query.client) {
                        if (token && token.hasOwnProperty('access_token')) {

                            return token;
                        }
                    }


                }

            } catch (ex) {

            }
        }

        return undefined;

    },

    wrapToken: function (token, req) {

        if (token) {
            token.client =  req.query.client;
            return token;
        }

    },

    set: function (token, req, res) {

        token = this.wrapToken(token, req);

        if (token) {
            res.cookie(this.cookie.name, JSON.stringify(token), this.cookie);
        } else {
            res.clearCookie(this.cookie.name, {
                path: this.cookie.path || '/'
            });

        }

    }
};


module.exports = Token;